package com.mjk.common.web.getway.restful.filter.gzip;


import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletResponse;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class GZipOutputStream extends ServletOutputStream {
	private final HttpServletResponse response;

	private final GZIPOutputStream gzipStream;

	private final ByteArrayOutputStream byteArrayOutputStream;

	public GZipOutputStream(HttpServletResponse response) throws IOException {
		this.response = response;
		byteArrayOutputStream = new ByteArrayOutputStream();
		gzipStream = new GZIPOutputStream(byteArrayOutputStream);
	}

	public void write(int b) throws IOException {
		gzipStream.write(b);
	}
	@Override
	public void close() throws IOException {
		gzipStream.finish();
		byte[] content = byteArrayOutputStream.toByteArray();
		response.addHeader("Content-Encoding", "gzip");
		response.addHeader("Content-Length", Integer.toString(content.length));
		ServletOutputStream out = response.getOutputStream();
		out.write(content);
		out.close();
	}
	@Override
	public void flush() throws IOException {
		gzipStream.flush();
	}
	@Override
	public void write(byte[] b, int off, int len) throws IOException {
		gzipStream.write(b, off, len);
	}
	@Override
	public void write(byte[] b) throws IOException {
		gzipStream.write(b);
	}

	
	public boolean isReady() {		
		return false;
	}

	
	public void setWriteListener(WriteListener listener) {
		//do noting
	}	
}
